<template>
  <div>
    <!-- 提示框 -->
    <div
      v-if="showPopup"
      :style="popupStyle"
      class="popup"
    >
      <!-- 你选中的文本是: {{ selectedText }} -->
        <div style="border-right:1px solid #dcdfe6;padding-right:10px;">
          <img style="width:25px;" src="../../assets/chatGPT.png">
        </div>
        <div class="tool" @click.stop="copyAnswer(selectedText)">
          <el-icon><DocumentCopy /></el-icon>
          复制
        </div>
        <div class="tool" @click.stop="speak(selectedText)">
          <el-icon><Headset /></el-icon>
          朗读
        </div>
    </div>
  </div>
</template>

<script>
import { speakText } from '../../utils/index'
export default {
  name: 'TextSelector',
  data() {
    return {
      showPopup: false,
      selectedText: '',
      popupStyle: {
        position: 'absolute',
        background: '#fff',
        color: '#909399',
        padding: '5px',
        borderRadius: '3px',
        zIndex: 1000000000,
      }
    };
  },
  mounted() {
    document.addEventListener('mouseup', this.handleMouseUp);
  },
  beforeDestroy() {
    document.removeEventListener('mouseup', this.handleMouseUp);
  },
  methods: {
    handleMouseUp(event) {
      // 获取鼠标当前的位置
      const mouseX = event.clientX;
      const mouseY = event.clientY;

      const selection = window.getSelection();
      const selectedText = selection.toString();

      if (selectedText) {
        this.selectedText = selectedText;

        // 延迟显示提示框，避免干扰文本选中
        setTimeout(() => {
          this.showPopup = true;
          
          // 设置提示框位置为鼠标位置的下方
          this.popupStyle.left = `${mouseX - 100}px`;
          this.popupStyle.top = `${mouseY + 20}px`; // 向下偏移10像素，以避免与鼠标重叠

        }, 100); // 100ms 延迟
      } 
      else {
        setTimeout(() => {
          this.showPopup = false; // 如果没有选中文本则隐藏提示框
        }, 100); // 100ms 延迟
      }
    },
    copyAnswer(data){
      let elInput = document.createElement('textarea')
      elInput.value = data
      document.body.appendChild(elInput)
      // 选择对象
      elInput.select()
      // 执行浏览器复制命令
      this.$message.success('复制成功')
      document.execCommand("Copy")
      elInput.remove()
    },
    speak(translatedText){
      speakText(translatedText)
    },
  }
}
</script>

<style lang="scss" scoped>
.popup {
  position: absolute;
  background: #fff;
  color: #909399;
  border-radius: 3px;
  z-index: 1000000000000; 
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 200px;
  font-size: 14px;
  .tool{
    padding: 5px;
    cursor: pointer;
  }
  .tool:hover{
    background-color: #eee;
  }
}

</style>
